<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属用户" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入商品所属用户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原价" prop="oriPrice">
        <el-input
          v-model="queryParams.oriPrice"
          placeholder="请输入原价"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="现价" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入现价"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入商品所属分类"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品品牌" prop="brandId">
        <el-input
          v-model="queryParams.brandId"
          placeholder="请输入商品所属品牌"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收取类型" prop="sendType">
        <el-select v-model="queryParams.sendType" placeholder="请选择收取类型" clearable size="small">
          <el-option
            v-for="dict in sendTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['deal:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['deal:goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['deal:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['deal:goods:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品id" align="center" prop="goodsId" v-if="false"/>
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="商品所属用户" align="center" prop="userName" />
      <el-table-column label="原价" align="center" prop="oriPrice" />
      <el-table-column label="现价" align="center" prop="price" />
      <el-table-column label="商品主图" align="center" prop="pic" width="160">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img :src="scope.row.pic" height="200" >
            <img slot="reference" :src="scope.row.pic" height="30"/>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="品牌" align="center" prop="brandName" />
      <el-table-column label="收取类型" align="center" prop="sendType" :formatter="sendTypeFormat" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['deal:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['deal:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog
      :title="title" 
      :visible.sync="open"
      append-to-body
      fullscreen
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="用户ID" prop="goodsId">
              <el-input v-model="form.userId" placeholder="用户ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>

          <el-col :span="6.5">
            <el-form-item label="原价" prop="oriPrice">
              <el-input v-model="form.oriPrice" placeholder="请输入原价" />
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item label="现价" prop="price">
              <el-input v-model="form.price" placeholder="请输入现价" />
            </el-form-item>
          </el-col>

        </el-row>
        
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" rows="5" />
            </el-form-item>
          </el-col>

          <el-col :span="6.5">
            <el-form-item label="所属分类" prop="categoryId">
              <el-cascader
                v-model="form.categoryId"
                :options="categoryOptions"
                :props="cascaderProps"
                clearable
                @change="handleChange">
                <template slot-scope="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>

          <el-col :span="6.5">
            <el-form-item label="所属品牌" prop="brandId">
              <el-select v-model="form.brandId" placeholder="请选择品牌" clearable size="small">
                <el-option
                  v-for="brand in brandOptions"
                  :key="brand.brandId"
                  :label="brand.brandName"
                  :value="brand.brandId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          
        
        </el-row>
          
        <el-form-item label="商品主图">
          <imageUpload v-model="form.pic"/>
        </el-form-item>

        <el-form-item label="商品图片">
          <imageListUpload v-model="form.picsArray" :urls="urls" :limit=5 />
        </el-form-item>

        <el-form-item label="收取类型" prop="sendType">
          <el-select v-model="form.sendType" placeholder="请选择收取类型">
            <el-option
              v-for="dict in sendTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods, exportGoods } from "@/api/deal/goods";
import { listBrand, getBrand, delBrand, addBrand, updateBrand, listBrandByCategoryId, exportBrand } from "@/api/deal/brand";
import { treeselect as categoryTreeselect, brandCategoryTreeselect } from "@/api/deal/category";
import ImageUpload from '@/components/ImageUpload';
import ImageListUpload from '@/components/ImageListUpload';

export default {
  name: "Goods",
  components: {
    ImageUpload,
    ImageListUpload
  },
  data() {
    return {
      urls: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 收取类型字典
      sendTypeOptions: [],
      // 状态(0未发布，1已发布，2交易中，3已卖出)字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: undefined,
        userId: undefined,
        oriPrice: undefined,
        price: undefined,
        categoryId: undefined,
        brandId: undefined,
        sendType: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "商品所属用户不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "现价不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "商品所属分类不能为空", trigger: "blur" }
        ],
        sendType: [
          { required: true, message: "收取类型不能为空", trigger: "change" }
        ],
      },
      cascaderProps: {
        value: "id",
        label: "label",
        children: "children",
        expandTrigger: 'hover',
      },
      categoryOptions: [],
      brandOptions: [],
    };
  },
  created() {
    this.getList();
    this.getDicts("hy_goods_send_type").then(response => {
      this.sendTypeOptions = response.data;
    });
    this.getDicts("hy_goods_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    handleChange(value) {
      if (value != undefined) {
        this.form.categoryId = value[value.length - 1];
        this.getBrandList(this.form.categoryId);
      }
    },
    /** 查询分类树结构 */
    getCategoryTreeselect() {
      categoryTreeselect().then(response => {
        this.categoryOptions = response.data;
      });
    },
    /** 查询品牌 */
    getBrandList(categoryId) {
      this.form.brandId = undefined;
      listBrandByCategoryId(categoryId).then(response => {
        this.brandOptions = response.data;
      });
    },
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 收取类型字典翻译
    sendTypeFormat(row, column) {
      return this.selectDictLabel(this.sendTypeOptions, row.sendType);
    },
    // 状态(0未发布，1已发布，2交易中，3已卖出)字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.urls = [];
      this.form = {
        goodsId: undefined,
        goodsName: undefined,
        description: undefined,
        userId: undefined,
        oriPrice: undefined,
        price: undefined,
        pic: undefined,
        pics: undefined,
        picsArray: [],
        categoryId: undefined,
        brandId: undefined,
        sendType: undefined,
        createTime: undefined,
        updateTime: undefined,
        status: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategoryTreeselect();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getCategoryTreeselect();
      this.getBrandList(row.categoryId);
      const goodsId = row.goodsId || this.ids
      getGoods(goodsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
        this.formatFileListToUrls();
      });
    },

    // 格式化：String数组转对象数组
    formatFileListToUrls() {
      for (let url of this.form.picsArray) {
          this.urls.push({'url': url});
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.goodsId != null) {
            updateGoods(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsIds = row.goodsId || this.ids;
      this.$confirm('是否确认删除商品管理编号为"' + goodsIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGoods(goodsIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportGoods(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
